#pragma once

#include <windows.h>
#include <process.h>
#include <string>
#include "ThreadManager.h"

class CThread
{
public:
	CThread() :
      m_hThread(NULL), m_iThreadID(0)
	{        
	}
    CThread(std::string name) :
      m_hThread(NULL), m_iThreadID(0), m_strName(name)
    {
    }
	virtual ~CThread()
	{
        if( m_hThread )
        {
            WaitForSingleObject(m_hThread,INFINITE);
            CThreadManager::getInstance()->unregistThread(m_iThreadID);
            CloseHandle(m_hThread);
        }
	}
public:
    void start()
    {
        m_hThread = (HANDLE)_beginthreadex(0,0,entry,this,0,&m_iThreadID);        
    }
    void wait(DWORD dwTime=INFINITE)
    {
        WaitForSingleObject(m_hThread,dwTime);
        delete this;
    }    
public:
    unsigned getThreadID() 
    { 
        return m_iThreadID;
    }
    std::string getName()
    {
        return m_strName;
    }
protected:
    static unsigned __stdcall entry(void* p)
    {
        CThreadManager::getInstance()->registThread(((CThread*)p)->getThreadID(), (CThread*)p);
        reinterpret_cast<CThread*>(p)->run();
        return 0;
    }
    virtual void run() = 0;

private:
    HANDLE      m_hThread;
    unsigned    m_iThreadID;
    std::string m_strName;
};